package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.ResourceBundle;

public class DemoSocketServer {
	private ServerSocket server;
	private ResourceBundle rb;
	
	public void init(){
		rb = ResourceBundle.getBundle("server/server");
	}
	
	public void start() throws IOException{
		server = new ServerSocket();
		InetSocketAddress address = new InetSocketAddress(rb.getString("binding.ip"), Integer.parseInt(rb.getString("binding.port")));
		server.bind(address);
		//server.setSoTimeout(Integer.parseInt(rb.getString("timeout")));
		
		System.out.println("Server has started... Waiting for Request!");
		while(true){
			Socket req = server.accept();
			System.out.println("Client Connect Successfully , ip : "+req.getInetAddress().getHostAddress());
			ReqHandler rh = new ReqHandler();
			rh.so = req;
			new Thread(rh).start();
		}
	}
	
	public static void main(String[] args) throws IOException {
		DemoSocketServer ds = new DemoSocketServer();
		ds.init();
		ds.start();
	}
}

class ReqHandler implements Runnable{
	Socket so;
	
	public void run() {
		try {
			InputStream in = so.getInputStream();
			ByteBuffer bb = ByteBuffer.allocate(4096);
			while(in.available() == 0){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			byte[] bytes = new byte[in.available()];
			in.read(bytes);
			bb.put(bytes);
			
			OutputStream out = so.getOutputStream();
			out.write(bb.array());
			out.flush();
			
			/*in.close();
			out.close();
			so.close();*/
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}